package top.hkyzf.study.j2se.juc;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 阻塞队列 API
 * 方法类型 抛出异常   特殊值    阻塞    超时
 *   插入   add(e)     offer(e)  put(e)  offer(e,time,unit)
 *   移除   remove(e)  poll()    take()  poll(time,unit)
 *   检查   element()  peek()    无      无
 *
 * @author 朱峰
 * @date 2021-3-15 16:14
 */
public class BlockingQueueDemo {

    public static void main(String[] args) throws InterruptedException {
        // List<String> list = new ArrayList<>();
        BlockingQueue blockingQueue = new ArrayBlockingQueue(3);
        System.out.println("1====================================================");
        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("b"));
        System.out.println(blockingQueue.add("c"));
        // System.out.println(blockingQueue.add("x")); // Queue full

        System.out.println(blockingQueue.element()); // 队首元素

        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        // System.out.println(blockingQueue.remove()); // java.util.NoSuchElementException

        System.out.println("2====================================================");
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("x")); // false

        System.out.println(blockingQueue.peek());

        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll()); // null

        System.out.println("3====================================================");
        blockingQueue.put("a");
        blockingQueue.put("a");
        blockingQueue.put("a");
        // blockingQueue.put("x"); // 阻塞

        blockingQueue.take();
        blockingQueue.take();
        blockingQueue.take();
        // blockingQueue.take(); // 阻塞

        System.out.println("4====================================================");
        System.out.println(blockingQueue.offer("a", 2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.offer("a", 2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.offer("a", 2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.offer("x", 2L, TimeUnit.SECONDS));

        System.out.println(blockingQueue.poll(2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.poll(2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.poll(2L, TimeUnit.SECONDS));
        System.out.println(blockingQueue.poll(2L, TimeUnit.SECONDS));
    }
}
